package com.feiyu.auth.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.feiyu.common.exception.GlobalException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author tang ming
 * @since 2021/11/29 12:08
 */
public class SecureUtil {

    public static JWTVerifier verifier = JWT.require(Algorithm.HMAC256(Constants.SING_KEY)).build();

    public static TokenInfo createJWT(Map<String, String> user, String audience, String issuer) {
        Calendar nowTime=Calendar.getInstance();
        nowTime.add(Calendar.HOUR,Constants.DEFAULT_TOKEN_TIME);
        //过期时间
        Date expiresTime=nowTime.getTime();

        JWTCreator.Builder builder= JWT.create()
                .withAudience(audience) //签发对象
                .withIssuedAt(new Date()) //发行时间
                .withExpiresAt(expiresTime) //有效时间
                .withIssuer(issuer);
        user.forEach(builder::withClaim);
        String token=builder.sign(Algorithm.HMAC256(Constants.SING_KEY));
        return new TokenInfo(token,Constants.DEFAULT_TOKEN_TIME);
    }

    public static Map<String, Claim> decodeToken(String token)  {
        try {
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaims();
        } catch (Exception e) {
            throw new GlobalException(AuthCode.TOKEN_INVALID);
        }
    }

    public static boolean isExpire(String token){
        try {
            DecodedJWT jwt = verifier.verify(token);
        } catch (Exception e) {
            return true;
        }
        return false;
    }
}
